package com.sinaapp.kltq.dinosaurweather;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sinaapp.kltq.data.WeatherDay;
import com.sinaapp.kltq.data.WeatherRealTime;
import com.sinaapp.kltq.weathermanager.WeatherManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link RealtimeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RealtimeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RealtimeFragment extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RealtimeFragment.
     */
    public static RealtimeFragment newInstance(String param1, String param2) {
        RealtimeFragment fragment = new RealtimeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public RealtimeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_realtime, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onStart() {
        WeatherManager wm = new WeatherManager(getActivity().getApplicationContext());
        // 获取城市
        int cityIndex;
        int activityLayoutId;
        if (getActivity().getClass() == FlipWhiteActivity.class) {
            cityIndex = ((FlipWhiteActivity)getActivity()).cityIndex;
            activityLayoutId = R.id.whiteTotal;
        } else {
            cityIndex = ((FlipBlackActivity)getActivity()).cityIndex;
            activityLayoutId = R.id.blackTotal;
        }
        String city = wm.getCityList().get(cityIndex).city;
        // 准备数据
        String wendu;
        String type;
        String high;
        String low;
        String detailWendu;
        String shidu;
        String fengxiang;
        String fengli;
        // 获取数据
        WeatherRealTime realTimeData = wm.getRealTimeWeather(city);
        WeatherDay dayData = wm.getForecastWeather(city).get(1);
        // 获取更新日
        Date updateDate = wm.getUpdateDate(city);
        if (updateDate == null) {
            wendu = " ";
            type = detailWendu = shidu = fengxiang = fengli = "N/A";
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
            Date today = new Date(System.currentTimeMillis());
            // 根据更新日载入数据
            if (sdf.format(today).compareTo(sdf.format(updateDate)) == 0) {   // 今日更新
                wendu = "" + realTimeData.wendu;
                if (today.getHours() > 8 && today.getHours() < 20) {
                    type = dayData.dayType;
                } else {
                    type = dayData.nightType;
                }
                high = dayData.high.substring(3);
                high = high.substring(0, high.length() - 1);
                low = dayData.low.substring(3);
                low = low.substring(0, low.length() - 1);
                detailWendu = low + "-" + high;
                shidu = realTimeData.shidu;
                fengxiang = realTimeData.fengxiang;
                fengli = realTimeData.fengli;
            } else {    // 之前更新
                // 找到新的dayData
                dayData = null;
                for (WeatherDay day : wm.getForecastWeather(city)) {
                    if (day.date.substring(0, 4).compareTo(sdf.format(today)) == 0) {
                        dayData = day;
                    }
                }
                // 更新日期过早
                if (dayData == null) {
                    wendu = " ";
                    type = detailWendu = shidu = fengxiang = fengli = "N/A";
                } else {
                    // 有本地缓存
                    wendu = " ";
                    shidu = "N/A";
                    high = dayData.high.substring(3);
                    high = high.substring(0, high.length() - 1);
                    low = dayData.low.substring(3);
                    low = low.substring(0, low.length() - 1);
                    detailWendu = low + "-" + high;
                    if (today.getHours() > 8 && today.getHours() < 20) {
                        type = dayData.dayType;
                        fengxiang = dayData.dayFx;
                        fengli = dayData.dayFl;
                    } else {
                        type = dayData.nightType;
                        fengxiang = dayData.nightFx;
                        fengli = dayData.nightFl;
                    }
                }
            }
        }
        // 显示数据
        // 根据天气获取天气图片
        int typeImgId = R.drawable.na;
        int typeBkImgId = -1;
        String typeImg = type;
        boolean tooDark = false;
        if (type.compareTo("雷阵雨") != 0 && type.length() > 2) {
            typeImg = type.substring(type.length() - 2, type.length());
        }
        if (typeImg.compareTo("晴") == 0) {
            typeImgId = R.drawable.sunny;
            typeBkImgId = R.drawable.sunny_bk;
        } else if (typeImg.compareTo("多云") == 0) {
            typeImgId = R.drawable.cloud;
            typeBkImgId = R.drawable.cloud_bk;
        } else if (typeImg.compareTo("大雨") == 0 || type.compareTo("中雨") == 0 || type.compareTo("小雨") == 0) {
            typeImgId = R.drawable.rain;
            typeBkImgId = R.drawable.rain_bk;
            // 需要设置颜色
            tooDark = true;
        } else if (typeImg.compareTo("阵雨") == 0) {
            typeImgId = R.drawable.shower;
            typeBkImgId = R.drawable.shower_bk;
        } else if (typeImg.compareTo("雷阵雨") == 0) {
            typeImgId = R.drawable.thundershower;
            typeBkImgId = R.drawable.thundershower_bk;
            // 需要设置颜色
            tooDark = true;
        } else if (typeImg.compareTo("暴雨") == 0) {
            typeImgId = R.drawable.storm;
            typeBkImgId = R.drawable.storm_bk;
            // 需要设置颜色
            tooDark = true;
        } else if (typeImg.compareTo("雪") == 0) {
            typeImgId = R.drawable.snow;
            typeBkImgId = R.drawable.snow_bk;
        } else if (typeImg.compareTo("晴转多云") == 0) {
            typeImgId = R.drawable.sunny2cloud;
            typeBkImgId = R.drawable.cloud_bk;
        }
        // 显示背景
        if (typeBkImgId != -1) {
            RelativeLayout layout = ((RelativeLayout) getActivity().findViewById(activityLayoutId));
            if (layout != null) {
                layout.setBackgroundResource(typeBkImgId);
            }
        }
        if (tooDark) {  // 修改颜色
            // 文字颜色
            ((TextView) getActivity().findViewById(R.id.titleCity)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.titleDate)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.updateTimeText)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeMainWendu)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeMainTypeText)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeDetailTypeText)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeDetailWendu)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realtimeDetailWenduTitle)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeDetailShidu)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeDetailShiduTitle)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeDetailFengxiang)).setTextColor(Color.WHITE);
            ((TextView) getActivity().findViewById(R.id.realTimeDetailFengli)).setTextColor(Color.WHITE);
            // 分隔线颜色
            ((View) getActivity().findViewById(R.id.titleLine)).setBackgroundColor(Color.WHITE);
            ((View) getActivity().findViewById(R.id.updateTimeLine)).setBackgroundColor(Color.WHITE);
            // 按钮颜色
            ((ImageView) getActivity().findViewById(R.id.titleShareBtn)).setImageResource(R.drawable.btn_share_w);
            ((ImageView) getActivity().findViewById(R.id.updateTimeBtn)).setImageResource(R.drawable.btn_refresh_w);
        }
        // 显示主要信息
        ((TextView) getActivity().findViewById(R.id.realTimeMainWendu)).setText(wendu);
        ((TextView) getActivity().findViewById(R.id.realTimeMainTypeText)).setText(type);
        // 显示细节信息
        ((ImageView) getActivity().findViewById(R.id.realTimeDetailTypeImg)).setImageResource(typeImgId);
        ((TextView) getActivity().findViewById(R.id.realTimeDetailTypeText)).setText(type);
        ((TextView) getActivity().findViewById(R.id.realTimeDetailWendu)).setText(detailWendu);
        ((TextView) getActivity().findViewById(R.id.realTimeDetailShidu)).setText(shidu);
        ((TextView) getActivity().findViewById(R.id.realTimeDetailFengxiang)).setText(fengxiang);
        ((TextView) getActivity().findViewById(R.id.realTimeDetailFengli)).setText(fengli);
        super.onStart();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

}
